<template>
  <div>
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="Number(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form
        :model="addForm"
        ref="addform"
        :rules="rules"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="el"
                  v-for="(el, ind) in item.attr_vals"
                  :key="ind"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="obj"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor
              ref="myTextEditor"
              v-model="addForm.goods_introduce"
            ></quill-editor>

            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="addBtn" @click="addGood"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="picVisible" width="50%">
      <img :src="previewPath" width="100%" />
    </el-dialog>
  </div>
</template>
<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
export default {
  name: "",
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      cateList: [], //商品分类数据
      manyData: [], //商品动态参数数据
      onlyData: [], //商品静态属性数据
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      obj: {
        //图片上传组件的请求头
        Authorization: window.sessionStorage.getItem("token"),
      },
      previewPath: "", //预览的图片的路径
      picVisible: false, //控制图片预览窗口的显示隐藏
    };
  },
  created() {
    this.getCateData();
  },
  components: {
    quillEditor,
  },
  methods: {
    // 获取商品分类数据
    async getCateData() {
      this.axios
        .get("https://www.liulongbin.top:8888/api/private/v1/categories")
        .then((res) => {
          //   console.log(res);
          if (res.data.meta.status !== 200) {
            return this.$message.error("获取商品分类失败");
          }
          this.cateList = res.data.data;
        });
    },
    // 级联选择器触发的方法
    handleChange() {
      // 如果选择分类时没有选第三级
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        this.$message.warning("只能选择三级商品分类");
      }
    },
    // 切换左侧标签之前的钩子，如果返回false则不能切换
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },

    // 左侧标签页的点击事件
    async tabClicked() {
      // 证明点击的是商品参数
      if (this.activeIndex === "1") {
        // 请求接口
        this.axios
          .get(
            `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes`,
            {
              params: { sel: "many" },
            }
          )
          .then((res) => {
            // console.log(res);
            if (res.data.meta.status !== 200) {
              return this.$message.error("获取商品动态参数失败");
            }
            res.data.data.forEach((item) => {
              item.attr_vals =
                item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
            });
            this.manyData = res.data;
          });
      } else if (this.activeIndex === "2") {
        this.axios
          .get(
            `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes`,
            {
              params: { sel: "only" },
            }
          )
          .then((res) => {
            // console.log(res);
            if (res.data.meta.status !== 200) {
              return this.$message.error("获取商品静态属性失败");
            }
            this.onlyData = res.data.data;
          });
      }
    },

    // 图片预览效果的操作
    handlePreview(file) {
      // console.log(file);
      this.previewPath = file.response.data.url;
      this.picVisible = true;
    },
    // 移除图片的操作
    handleRemove(file) {
      // 1.获取将要删除的图片的临时路径
      // console.log(file);
      const filePath = file.response.data.tmp_path;
      // 2.从pics数组中，找到这个图片对应的索引值
      let index = this.addForm.pics.findIndex((item) => {
        return item.pic == filePath;
      });
      // 3.调用数组的splice方法，把该图片从pics数组中移除掉
      this.addForm.pics.splice(index, 1);
      console.log(this.addForm.pics);
    },
    // 图片上传成功时执行的函数
    uploadSuccess(res, file, fileList) {
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("图片上传失败");
      }
      // 把获取到的图片临时路径放在一个对象里
      const obj = { pic: res.data.tmp_path };
      this.addForm.pics.push(obj); //追加到pics数组里
      this.$message.success(res.meta.msg);
    },

    // 添加商品的操作
    addGood() {
      this.$refs.addform.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项");
        }
        // 否则就执行相应的业务逻辑
        // 先把addForm深拷贝一份，否则会与级联选择器绑定的goods_cat发生矛盾
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        // 处理动态参数
        this.manyData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.onlyData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(newInfo);
        });
        form.attrs = this.addForm.attrs;
        this.axios
          .post("https://www.liulongbin.top:8888/api/private/v1/goods", form)
          .then((res) => {
            console.log(res);
            if (res.data.meta.status != 201) {
              return this.$message.error("添加商品失败");
            }
            this.$message.success("添加商品成功");
            this.$router.push("/goods");
          });
      });
    },
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addBtn {
  margin-top: 10px;
}
.quill-editor {
  min-height: 300px;
}
</style>